import { DeleteOutlined, EditOutlined, ExclamationCircleFilled } from "@ant-design/icons";
import { Button, Card, Flex, List, Modal, Space, Typography, message, theme } from "antd";
import React, { useEffect, useRef, useState } from "react";
import { useEmotionCss } from "@ant-design/use-emotion-css";
import {
	changeSort,
	getPageList as getCategaryPageList,
	getCategray,
	remove,
	save,
	update
} from "@/services/api/module/message/categray";
import { ModalForm, ProFormInstance, ProFormText } from "@ant-design/pro-components";
import { DndContext, DragEndEvent, KeyboardSensor, PointerSensor, useSensor, useSensors } from "@dnd-kit/core";
import { SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
const { useToken } = theme;
import { CSS } from "@dnd-kit/utilities";
import IconFont from "@/components/IconFont";
const CategaryList: React.FC<{ onSelect: (id: number | undefined) => void }> = ({ onSelect = () => {} }) => {
	const [categaryData, setCategrayData] = useState<any>([]);
	const [selectIndex, setSelectIndex] = useState<any>();
	const [currentId, setCurrentId] = useState<any>(undefined);
	const [formOpen, setFormOpen] = useState<any>();
	const formRef = useRef<ProFormInstance>();
	useEffect(() => {
		getCategaryList();
	}, []);
	const getCategaryList = () => {
		getCategaryPageList().then(res => {
			setCategrayData(res?.data);
		});
	};

	useEffect(() => {
		if (currentId) {
			getCategray(currentId).then(data => {
				formRef?.current?.setFieldsValue(data);
			});
		}
	}, [currentId]);
	const handleFormOpen = (id: number) => {
		setCurrentId(id);
		setFormOpen(true);
	};
	const handleCancel = () => {
		setFormOpen(false);
		setCurrentId(undefined);
	};
	const handleFinish = async (values: Record<string, any>) => {
		if (currentId) {
			//修改
			update({ id: currentId, ...values })
				.then(res => {
					message.success(res.msg);
					handleCancel();
					getCategaryList();
					return Promise.resolve();
				})
				.catch(err => {
					return Promise.reject();
				});
		} else {
			//新增
			save(values)
				.then(res => {
					message.success(res.msg);
					handleCancel();
					getCategaryList();
					return Promise.resolve();
				})
				.catch(err => {
					return Promise.reject();
				});
		}
	};
	const handleRemove = (name: string, id: number) => {
		Modal.confirm({
			title: "删除警告",
			icon: <ExclamationCircleFilled />,
			content: `确定删除该：${name} 消息模板分类, 如果分类下存在模板，则无法删除`,
			okText: "确认",
			cancelText: "取消",
			onOk() {
				return new Promise((reslove, reject) => {
					remove(id)
						.then((res: any) => {
							message.success(res.msg);
							getCategaryList();
							reslove(true);
						})
						.catch(() => {
							reject(true);
						});
				});
			},
			onCancel() {}
		});
	};
	const handleDragEnd = (event: DragEndEvent) => {
		const { active, over } = event;
		console.log(active, over);

		if (active?.id !== over?.id) {
			changeSort(active?.id as number, over?.id as number).then(res => {
				message.success(res?.msg);
				getCategaryList();
			});
		}
	};
	const sensors = useSensors(
		useSensor(PointerSensor),
		useSensor(KeyboardSensor, {
			coordinateGetter: sortableKeyboardCoordinates
		})
	);

	return (
		<>
			<Card
				styles={{
					header: {
						padding: "0 15px"
					},
					body: {
						padding: "5px 10px"
					}
				}}
				title="模板分类"
				extra={
					<Button
						type="link"
						onClick={() => {
							setFormOpen(true);
						}}
					>
						创建分类
					</Button>
				}
				style={{ height: "calc(100vh - 130px)" }}
			>
				<DndContext onDragEnd={handleDragEnd} sensors={sensors}>
					<SortableContext items={categaryData} strategy={verticalListSortingStrategy}>
						<List<API.System.CategaryVo>
							style={{ overflow: "auto", minHeight: "calc(100vh - 90px)", marginTop: "4px" }}
							split={false}
							header={null}
							dataSource={categaryData}
							renderItem={(item, index) => (
								<SortableItem
									key={index}
									index={index}
									selectIndex={selectIndex}
									id={item?.id}
									item={item}
									onSelect={(id: number) => {
										if (selectIndex === item?.id) {
											setSelectIndex(undefined);
											onSelect(undefined);
											return;
										}
										setSelectIndex(id);
										onSelect(item?.id);
									}}
									onEditor={(id: number) => {
										handleFormOpen(id);
									}}
									onRemove={(name: string, id: number) => {
										handleRemove(name, item?.id);
									}}
								/>
							)}
						/>
					</SortableContext>
				</DndContext>
			</Card>
			<ModalForm
				width={450}
				formRef={formRef}
				title={currentId ? "修改分类" : "创建分类"}
				grid={true}
				open={formOpen}
				modalProps={{
					destroyOnClose: true,
					onCancel: () => {
						handleCancel();
					}
				}}
				onFinish={handleFinish}
			>
				<ProFormText
					colProps={{ xs: 24, md: 24, lg: 24 }}
					name="name"
					rules={[
						{
							required: true,
							message: "请输入分类名称"
						}
					]}
					label="分类名称"
				/>
			</ModalForm>
		</>
	);
};

const SortableItem: React.FC<any> = ({ id, onSelect, item, onEditor, onRemove, selectIndex }) => {
	const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: id });
	const { token } = useToken();
	const style = {
		transform: CSS.Transform.toString(transform),
		transition
	};
	const categoryClassName = useEmotionCss(({ token }) => {
		return {
			width: "100%",
			height: "40px",
			padding: "0 10px",
			borderRadius: token.borderRadiusSM,
			"&:hover": {
				background: token.colorBgTextHover,
				cursor: "pointer"
			},
			".oper": {
				display: "none"
			},
			"&:hover .oper": {
				display: "block"
			}
		};
	});
	return (
		<List.Item
			ref={setNodeRef}
			{...attributes}
			onClick={() => {
				console.log("selectIndex");
				onSelect(id);
			}}
			key={id}
			style={{ ...style, width: "100%", padding: "0", background: id == selectIndex ? token.colorBgTextHover : "" }}
		>
			<Flex justify="space-between" align="center" className={categoryClassName}>
				<Space>
					<IconFont {...listeners} type="icon-tuozhuai" />
					<Typography.Text ellipsis>{item?.name}</Typography.Text>
				</Space>
				<div className={"oper"}>
					<Space size={10}>
						<Typography.Link
							onClick={() => {
								onEditor(item?.id);
							}}
						>
							<EditOutlined />
						</Typography.Link>
						<Typography.Link
							type="danger"
							onClick={() => {
								onRemove(item?.name, item?.id);
							}}
						>
							<DeleteOutlined />
						</Typography.Link>
					</Space>
				</div>
			</Flex>
		</List.Item>
	);
};
export default CategaryList;
